﻿using Casamiel.API.Application;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Services;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Application;
using Casamiel.Common;
using Casamiel.Domain;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using NLog;
using System;
using System.Threading.Tasks;

namespace Casamiel.API.Controllers.V1
{
    /// <summary>
    /// 
    /// </summary>
    /// 
    [ApiVersion("1.0")]
    [Produces("application/json")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    [Authorize]
    [ApiController]
    public class AccountController : Controller
    {
        private IMobileCheckCode _mobileCheckCode;
        private readonly IMemberService _memberRepository;
        private ICacheService _cacheService;
        private readonly IUserLogService _userLog;
        private readonly IIcApiService _iicApiService;
        private readonly CasamielSettings _casamielSettings;
        private readonly IStoreApiService _storeApiService;
        private readonly NLog.ILogger logger = LogManager.GetLogger("BizInfo");

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mobileCheckCode"></param>
        /// <param name="memberRepository"></param>
        /// <param name="cacheService"></param>
        /// <param name="userLog"></param>
        /// <param name="iicApiService"></param>
        /// <param name="storeApiService"></param>
        /// <param name="snapshot"></param>
        public AccountController(
            IMobileCheckCode mobileCheckCode,
            IMemberService memberRepository,
            ICacheService cacheService,
            IUserLogService userLog,
            IIcApiService iicApiService, IStoreApiService storeApiService,
            IOptionsSnapshot<CasamielSettings> snapshot)
            
        {
            if (snapshot is null) {
                throw new ArgumentNullException(nameof(snapshot));
            }

            this._mobileCheckCode = mobileCheckCode;
            this._memberRepository = memberRepository;
            this._memberRepository = memberRepository;
            this._cacheService = cacheService;
            _userLog = userLog;
            _iicApiService = iicApiService;
            _storeApiService = storeApiService;
            _casamielSettings = snapshot.Value;
        }
        /// <summary>
        /// 修改信息
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[Action]")]
        [TypeFilterAttribute(typeof(CheckLoginAttribute))]
        public async Task<IActionResult> ModifyMemberInfo([FromBody] AccountReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            ConsoleHelper.DoLog(data, Request);
            var mobile = MemberHelper.GetMobile(token);
            var member = await _memberRepository.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            member.Nick = data.Nick;
            member.Sex = data.Sex;
            member.TrueName = data.TrueName;
            member.Birthday = data.Birthday;
            member.Email = data.Email;
            member.InvitationCode = data.InvitationCode;
            await _memberRepository.UpdateAsync<ICasaMielSession>(member).ConfigureAwait(false);

            if (_casamielSettings.ApiName == "doncoApi" && !string.IsNullOrEmpty(data.InvitationCode)) {
                try {
                    await _storeApiService.AddReferral(mobile, data.InvitationCode).ConfigureAwait(false);
                } catch (Exception ex) {
                    logger.Error($"AddReferral:{ex.StackTrace}");
                }

            }
            _cacheService.Replace(token, member);
            var logdata = new UserLog { Url = Request.HttpContext.Request.Path, OPInfo = "修改资料", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
            await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
            var a = new { code = 1, msg = "修改成功！" };
            return new JsonResult(a);
        }
        /// <summary>
        /// 用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>
        /// {"code": 0,"data": { "mobile": "18605888772", "nick": "stone","birthday": "1991-09-15T00:00:00","sex": 1,"trueName": "shi","invitationCode":""}}
        /// </remarks>
        [HttpPost]
        [HttpGet]
        [Route("[Action]")]
        [TypeFilterAttribute(typeof(CheckLoginAttribute))]
        public async Task<IActionResult> GetMemberInfo([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            var member = await _memberRepository.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            var data = new { Mobile = member.Mobile, Nick = member.Nick, Birthday = member.Birthday, Sex = member.Sex, TrueName = member.TrueName, Email = member.Email,member.InvitationCode };
            var a = new { code = 0, data = data };
            return new JsonResult(a);
        }

    }
}